/* 这是修改密码的hooks */
import axios from "axios"
import { ref, reactive, unref } from "vue"
//存储登录时候的id,用户名和用户等级
import { useUserStore } from "../../stores/useUserStore"
import router from "@/router"
//导入element-plus 提示框
import { ElMessage } from "element-plus"
export const updatePassword = () => {
  const UserStore = useUserStore()
  //修改密码弹框的显示隐藏
  const userUpdatePassword = ref(false)
  //存储input内容
  const userPassword = reactive({
    username: "",
    password: "",
    newpassword: "",
    confirmnewpassword: "",
  })
  //表单验证
  const loginFormUpdate = ref()

  const validatePassA = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请输入新密码"))
    } else {
      if (userPassword.confirmnewpassword !== "") {
        if (!loginFormUpdate.value) return
        loginFormUpdate.value.validateField("confirmnewpassword", () => null)
      }
      callback()
    }
  }
  const validatePassB = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请确认新密码"))
    } else if (value !== userPassword.newpassword) {
      callback(new Error("两次密码不一致"))
    } else {
      callback()
    }
  }
  const validatePassC = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请输入原密码"))
    } else if (value !== UserStore.userPassword) {
      callback(new Error("密码不正确"))
    } else {
      callback()
    }
  }
  const userPasswordRules = reactive({
    password: [{ validator: validatePassC, trigger: "blur" }],
    newpassword: [{ validator: validatePassA, trigger: "blur" }],
    confirmnewpassword: [{ validator: validatePassB, trigger: "blur" }],
  })
  function handleUpdatePassword() {
    userUpdatePassword.value = true
    userPassword.username = UserStore.userName
  }
  //点击修改密码验证
  const submitUpdate = () => {
    const form = unref(loginFormUpdate)
    // console.log(form)
    if (!form) return
    //整体表单验证
    form.validate((valid) => {
      if (valid) {
        //检测成功
        // console.log("valid", valid)
        axios
          .put(`http://localhost:3000/ggusers/${UserStore.userId}`, {
            user_name: UserStore.userName,
            user_password: userPassword.newpassword,
            user_type: UserStore.userType,
            user_onlinestatus: "0",
            user_other: UserStore.userOther,
          })
          .then((res) => {
            // console.log(res, "修改成功")
            const { code, message } = res.data

            router.push("/login")
            //清空token
            localStorage.setItem("token", "")
            ElMessage({ message, type: "success" })
          })


      }
    })
  }
  return {
    handleUpdatePassword, //点击修改弹框状态
    userUpdatePassword, //弹框状态
    userPassword, //接收input内容
    userPasswordRules, //表单验证规则
    submitUpdate, //点击修改密码
    loginFormUpdate, //表单验证
  }
}
